package com.jetbrains.kmpapp.feature.payment

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import platform.Foundation.NSError
import platform.StoreKit.*
import platform.darwin.NSObject

actual object InAppPurchaseService { // 实现交易观察者代理协议

    private var currentProductIdentifier: String? = null
    private var currentApplicationUsername: String? = null

    private val _purchaseResultFlow = MutableSharedFlow<PurchaseResult>(extraBufferCapacity = 1)
    actual val purchaseResultFlow: Flow<PurchaseResult> = _purchaseResultFlow.asSharedFlow()

    private val productsRequestDelegate by lazy {
        ProductsRequestDelegate(
            onSuccess = { products ->

            },
            onFailure = { request, error ->

            }
        )
    }

    private val paymentTransactionObserver by lazy {
        PaymentTransactionObserver()
    }

    init {
        // 在服务初始化时，将自身添加为支付队列的观察者
        SKPaymentQueue.defaultQueue().addTransactionObserver(paymentTransactionObserver)
        println("KMP StoreKit: Initialized and added as transaction observer.")
    }

    actual fun purchase(productId: String, uuid: String) {
        if (currentApplicationUsername == uuid) {
            return
        }

        currentProductIdentifier = productId
        currentApplicationUsername = uuid

        val productRequest = SKProductsRequest(setOf(productId))
        productRequest.delegate = productsRequestDelegate
        productRequest.start()

        println("KMP StoreKit: Added payment for product: $productId")
    }

    actual fun restorePurchases() {
        SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
        println("KMP StoreKit: Initiating restore completed transactions.")
    }

    // 确保在 ViewModel/Service 被销毁时移除观察者
    actual fun dispose() {
        SKPaymentQueue.defaultQueue().removeTransactionObserver(paymentTransactionObserver)
        println("KMP StoreKit: Removed as transaction observer.")
    }

}

private class ProductsRequestDelegate(
    val onSuccess: (List<SKProduct>) -> Unit,
    val onFailure: (SKRequest, Throwable) -> Unit
): NSObject(), SKProductsRequestDelegateProtocol {
    override fun productsRequest(request: SKProductsRequest, didReceiveResponse: SKProductsResponse) {
        val availableProducts = didReceiveResponse.products.mapNotNull { it as? SKProduct }
        val invalidProductIDs = didReceiveResponse.invalidProductIdentifiers

        println("KMP StoreKit: Fetched ${availableProducts.size} products.")
        if (!invalidProductIDs.isEmpty()) {
            println("KMP StoreKit: Invalid Product IDs: $invalidProductIDs")
        }

        if (availableProducts.isEmpty()) {
            onFailure(request, IllegalStateException("No product found."))
        } else {
            onSuccess(availableProducts)
        }
    }

    override fun request(request: SKRequest, didFailWithError: NSError) {
        onFailure(request, IllegalStateException(didFailWithError.localizedDescription))
    }
}

private class PaymentTransactionObserver(

): NSObject(), SKPaymentTransactionObserverProtocol {

    override fun paymentQueue(queue: SKPaymentQueue, updatedTransactions: List<*>) {
//        for (transaction in updatedTransactions) {
//            transaction as SKPaymentTransaction // 类型转换
//            when (transaction.transactionState) {
//                SKPaymentTransactionState.SKPaymentTransactionStatePurchased -> {
//                    println("KMP StoreKit: Transaction Purchased: ${transaction.payment.productIdentifier}")
//                    // IMPORTANT: 发送收据到后端进行验证
//                    // val receiptURL = platform.Foundation.NSBundle.mainBundle().appStoreReceiptURL
//                    // val receiptData = receiptURL?.let { platform.Foundation.NSData.dataWithContentsOfURL(it) }
//                    // ... 将 receiptData 发送给您的服务器 ...
//
//                    _purchaseResultFlow.tryEmit(
//                        PurchaseResult.Success(
//                            productId = transaction.payment.productIdentifier,
//                            transactionId = transaction.transactionIdentifier ?: "N/A"
//                        ))
//                    queue.finishTransaction(transaction) // 完成交易
//                    _transactionUpdatesFlow.tryEmit(transaction.payment.productIdentifier) // 通知更新
//
//                }
//                SKPaymentTransactionState.SKPaymentTransactionStateFailed -> {
//                    val errorMessage = transaction.error?.localizedDescription ?: "Unknown payment error."
//                    println("KMP StoreKit: Transaction Failed: ${transaction.payment.productIdentifier} - $errorMessage")
//                    _purchaseResultFlow.tryEmit(PurchaseResult.Error(errorMessage))
//                    queue.finishTransaction(transaction) // 完成失败的交易
//                }
//                SKPaymentTransactionState.SKPaymentTransactionStateRestored -> {
//                    println("KMP StoreKit: Transaction Restored: ${transaction.payment.productIdentifier}")
//                    // 解锁内容
//                    _purchaseResultFlow.tryEmit(
//                        PurchaseResult.Success(
//                            productId = transaction.payment.productIdentifier,
//                            transactionId = transaction.transactionIdentifier ?: "N/A"
//                        )) // 或一个专门的恢复成功类型
//                    queue.finishTransaction(transaction) // 完成恢复的交易
//                }
//                SKPaymentTransactionState.SKPaymentTransactionStateDeferred -> {
//                    println("KMP StoreKit: Transaction Deferred: ${transaction.payment.productIdentifier} (e.g., Ask to Buy)")
//                    _purchaseResultFlow.tryEmit(PurchaseResult.Deferred)
//                }
//                SKPaymentTransactionState.SKPaymentTransactionStatePurchasing -> {
//                    println("KMP StoreKit: Transaction Purchasing: ${transaction.payment.productIdentifier}")
//                    // 无需操作
//                }
//                else -> {
//                    println("KMP StoreKit: Unknown transaction state: ${transaction.transactionState.value}")
//                }
//            }
//        }
    }

    override fun paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
        println("KMP StoreKit: Restore completed transactions finished.")
        // 可以根据需要通知 commonMain 恢复完成
        if (queue.transactions.isEmpty()) {

        }
    }

    override fun paymentQueue(
        queue: SKPaymentQueue,
        restoreCompletedTransactionsFailedWithError: NSError
    ) {
        println("KMP StoreKit: Restore completed transactions failed with error: ${restoreCompletedTransactionsFailedWithError.localizedDescription}")
//        _purchaseResultFlow.tryEmit(PurchaseResult.Error("Restore failed: ${restoreCompletedTransactionsFailedWithError.localizedDescription}"))
    }

}